<?php 
class Admin_ConstantController extends Zend_Controller_Action{
	
	protected $_model = null;
	
	public function init(){
		$this->_model = new Application_Model_DbTable_Constant();
	}
	
	public function indexAction(){
		$filters = array();
		
		//từ khóa
		$keyword = $this->_request->getParam('keyword','');
		$filters['keyword']=$keyword;
		$this->view->keyword = $keyword;
		
		
		// sắp xếp | order
		$order = $this->_request->getParam('order',"");
		if($order!=""){
			list($orderBy,$orderType) = explode('-', $order);
		}else{
			$orderBy=null;
			$orderType=null;
		}
		
		
		//get item count per page
		$icpp = $this->_request->getParam('icpp',20);
		
		//get current page number
		$currentPage = $this->_request->getParam('page',1);
		
		$list = $this->_model->getList($filters,$orderType,$orderBy);
		
		// pagination
		$paginator = Zend_Paginator::factory($list);
		$paginator->setCurrentPageNumber($currentPage);
		$paginator->setItemCountPerPage($icpp);
		$paginator->setPageRange(5);
		
		//assign to view
		$this->view->paginator=$paginator;
	}
	
	public function insertAction(){
		$form = new Admin_Form_Constant();
		
		if($this->_request->isPost()){
			if($form->isValid($this->_request->getPost())){
				$row = $this->_model->createRow($_POST);
				$row->constant_alias = Cms_String_String::toAlias($row->constant_name);
				$row->constant_creation_time = date('Y-m-d H:i:s');
				// save to database
				$row->save();
				$this->_helper->flashMessenger('Thêm đối tượng thành công!');
				$this->_helper->redirector('index','constant','admin');
			}
		}
		$this->view->form = $form;
	}
	
	public function updateAction(){
		//get id from request
		$id = $this->_request->getParam('id');
		
		//lấy đối đượng dựa vào id
		$row = $this->_model->find($id)->current();
		
		if(!$row){
			echo "<p align=center>Dữ liệu không tồn tại!</p>";
		}else{
			$form = new Admin_Form_Constant();
			$form->removeElement('constant_code');
			if($this->_request->isPost()){
				if($form->isValid($this->_request->getPost())){
		
					$row->setFromArray($_POST);
					$row->constant_alias = Cms_String_String::toAlias($row->constant_name);
					$row->save();
					
					$this->_helper->flashMessenger('Cập nhật thành công!');
					$this->_helper->redirector('index','constant','admin');
				}
			}
			
			$form->populate($row->toArray());
				
			$this->view->form = $form;
		}
	}
	
	public function deleteAction(){
		
	}
}